package com.tencent.wxcloudrun.service;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.wxcloudrun.common.ThreadLocalUtils;
import com.tencent.wxcloudrun.common.Utils;
import com.tencent.wxcloudrun.dao.AdminUserMapper;
import com.tencent.wxcloudrun.model.AdminUser;
import com.tencent.wxcloudrun.response.AppException;
import com.tencent.wxcloudrun.response.ErrorCodeMsgEnum;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sts.v20180813.StsClient;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenRequest;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * ClassName: AdminUserService
 * Package: com.tencent.wxcloudrun.service
 * Description:
 *
 * @Date: 2023/1/23 2:04 PM
 * @Author: wht
 */
@Slf4j
@Service
public class AdminUserService {
    @Autowired
    AdminUserMapper adminUserMapper;

    public void addOneAdminUser(AdminUser adminUser) {
        try {
            adminUser.setPassword(Utils.encryptPassword("igelato123456"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        adminUserMapper.addOneAdminUser(adminUser);
    }

    public void resetAdminUserPassword(AdminUser adminUser) {
        try {
            adminUser.setPassword(Utils.encryptPassword("igelato123456"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        System.out.println(adminUser);
        adminUserMapper.updateOneAdminUserById(adminUser);
    }

    public void updateOneAdminUserById(AdminUser adminUser) {
        String password = adminUser.getPassword();
        if (password != null && !"".equals(password)) {
            try {
                adminUser.setPassword(Utils.encryptPassword(password));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
        adminUserMapper.updateOneAdminUserById(adminUser);
    }

    public PageInfo getAdminUserList(AdminUser adminUser) {
        PageHelper.startPage(adminUser.getPageNum(), adminUser.getPageSize());
        PageHelper.orderBy("id");
        List<AdminUser> userList = adminUserMapper.getAdminUserList(adminUser);

        for (AdminUser user : userList) {
            user.setRole_ids(JSON.parseArray(user.getRole_ids_json(), Integer.class));
        }

        PageInfo<AdminUser> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    public String login(AdminUser adminUser) {
        String password = adminUser.getPassword();
        if (password == null || "".equals(password)) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }
        try {
            adminUser.setPassword(Utils.encryptPassword(password));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        AdminUser res = adminUserMapper.getOneAdminUserByMobile(adminUser.getMobile());

        if (res == null) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }
        if (!res.getPassword().equals(adminUser.getPassword())) {
            throw new AppException(ErrorCodeMsgEnum.LOGIN_ERROR);
        }

        // 生成一个token
        String token = Utils.getNewToken();


        //  保存到数据库中
        res.setToken(token);
        res.setPassword(null);
        adminUserMapper.updateOneAdminUserById(res);

        return token;
    }

    public HashMap getCosTempToken() {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Properties properties = new Properties();
            File configFile = new File("local.properties");
            properties.load(new FileInputStream(configFile));

            Credential cred = new Credential(properties.getProperty("SecretId"), properties.getProperty("SecretKey"));
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sts.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            StsClient client = new StsClient(cred, properties.getProperty("Region"), clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GetFederationTokenRequest req = new GetFederationTokenRequest();
            req.setName("GetFederationToken");
            req.setPolicy("%7B%22statement%22%3A%5B%7B%22action%22%3A%5B%22name%2Fcos%3AHeadBucket%22%2C%22name%2Fcos%3AGetObject%22%2C%22name%2Fcos%3AHeadObject%22%2C%22name%2Fcos%3AOptionsObject%22%2C%22name%2Fcos%3APutObject%22%2C%22name%2Fcos%3APostObject%22%2C%22name%2Fcos%3ADeleteObject%22%2C%22name%2Fcos%3AInitiateMultipartUpload%22%2C%22name%2Fcos%3AUploadPart%22%2C%22name%2Fcos%3ACompleteMultipartUpload%22%2C%22name%2Fcos%3AAbortMultipartUpload%22%5D%2C%22effect%22%3A%22Allow%22%2C%22resource%22%3A%5B%22qcs%3A%3Acos%3Aap-beijing%3Auid%2F1257288972%3Asjz-1-1257288972%2Fgoods_img%2F*%22%5D%7D%5D%2C%22version%22%3A%222.0%22%7D");
            // 返回的resp是一个GetFederationTokenResponse的实例，与请求对象对应
            GetFederationTokenResponse resp = client.GetFederationToken(req);

            HashMap res = new HashMap();
            res.put("TmpSecretId", resp.getCredentials().getTmpSecretId());
            res.put("TmpSecretKey", resp.getCredentials().getTmpSecretKey());
            res.put("SecurityToken", resp.getCredentials().getToken());
            res.put("StartTime", Math.floor(ThreadLocalUtils.getTime() / 1000));
            res.put("ExpiredTime", resp.getExpiredTime());
            return res;
            // 输出json格式的字符串回包
//            System.out.println(GetFederationTokenResponse.toJsonString(resp));
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.WX_COS_ERROR);
//            System.out.println(e.toString());
//            return null;
        }
    }

    public AdminUser getOneAdminUserByToken(String token) {
        AdminUser adminUser = adminUserMapper.getOneAdminUserByToken(token);
        adminUser.setRole_ids(JSON.parseArray(adminUser.getRole_ids_json(), Integer.class));
        return adminUser;
    }


    public AdminUser getOneAdminUserById(Integer id) {
        AdminUser adminUser = adminUserMapper.getOneAdminUserById(id);
        adminUser.setRole_ids(JSON.parseArray(adminUser.getRole_ids_json(), Integer.class));
        return adminUser;
    }
}
